<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImportExportFile extends Model
{
    protected $fillable = [
        'original_name',
        'stored_name',
        'file_path',
        'file_type',
        'mime_type',
        'file_size',
        'file_extension',
        'operation_type',
        'module_name',
        'operation_description',
        'user_id',
        'user_name',
        'user_ip',
        'user_agent',
        'status',
        'total_records',
        'success_records',
        'failed_records',
        'error_message',
        'error_details',
        'filter_conditions',
        'export_fields',
        'import_mapping',
        'processed_at'
    ];

    protected $casts = [
        'file_size' => 'integer',
        'total_records' => 'integer',
        'success_records' => 'integer',
        'failed_records' => 'integer',
        'processed_at' => 'datetime',
        'error_details' => 'array',
        'filter_conditions' => 'array',
        'export_fields' => 'array',
        'import_mapping' => 'array',
    ];

    // 状态常量
    const STATUS_PENDING = 'pending';
    const STATUS_PROCESSING = 'processing';
    const STATUS_COMPLETED = 'completed';
    const STATUS_FAILED = 'failed';

    // 操作类型常量
    const OPERATION_IMPORT = 'import';
    const OPERATION_EXPORT = 'export';

    // 文件类型常量
    const FILE_TYPE_EXCEL = 'excel';
    const FILE_TYPE_CSV = 'csv';
    const FILE_TYPE_PDF = 'pdf';
    const FILE_TYPE_WORD = 'word';
    const FILE_TYPE_JSON = 'json';

    /**
     * 获取操作用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取文件大小格式化字符串
     */
    public function getFileSizeFormattedAttribute(): string
    {
        $bytes = $this->file_size;
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }

        return round($bytes, 2) . ' ' . $units[$i];
    }

    /**
     * 获取处理进度百分比
     */
    public function getProgressPercentageAttribute(): int
    {
        if ($this->status === self::STATUS_COMPLETED || $this->status === self::STATUS_FAILED) {
            return 100;
        }

        if ($this->total_records && $this->total_records > 0) {
            $processed = ($this->success_records ?? 0) + ($this->failed_records ?? 0);
            return min(100, intval(($processed / $this->total_records) * 100));
        }

        return 0;
    }

    /**
     * 检查是否可以删除
     * 导入导出文件必须永久保留，不允许删除
     */
    public function canBeDeleted(): bool
    {
        return false; // 永远不允许删除
    }

    /**
     * 获取状态标签
     */
    public function getStatusLabelAttribute(): string
    {
        return match($this->status) {
            self::STATUS_PENDING => '待处理',
            self::STATUS_PROCESSING => '处理中',
            self::STATUS_COMPLETED => '已完成',
            self::STATUS_FAILED => '失败',
            default => '未知状态'
        };
    }

    /**
     * 获取操作类型标签
     */
    public function getOperationTypeLabelAttribute(): string
    {
        return match($this->operation_type) {
            self::OPERATION_IMPORT => '导入',
            self::OPERATION_EXPORT => '导出',
            default => '未知操作'
        };
    }

    /**
     * 范围查询：按状态筛选
     */
    public function scopeByStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 范围查询：按操作类型筛选
     */
    public function scopeByOperationType($query, string $operationType)
    {
        return $query->where('operation_type', $operationType);
    }

    /**
     * 范围查询：按模块筛选
     */
    public function scopeByModule($query, string $moduleName)
    {
        return $query->where('module_name', $moduleName);
    }

    /**
     * 范围查询：按用户筛选
     */
    public function scopeByUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }
}
